package com.working.content

import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.widget.LinearLayout
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.just.agentweb.core.AgentWeb
import com.working.content.data.bean.Sku
import com.working.content.data.bean.jd.JDProductBean
import com.working.content.data.bean.jd.PriceBean
import com.working.content.databinding.ContentFragmentMainBinding
import com.working.libbase.base.BaseFragment
import com.working.libbase.route.RoutePath
import com.working.libcommon.exts.cast
import com.working.libcommon.exts.getString
import com.working.libcommon.exts.onClick
import com.working.libcommon.exts.parseJson
import com.working.libcommon.util.LogUtils
import com.working.libcommon.util.getType
import com.working.libview.widget.web.MiddlewareWebViewClient
import com.working.libview.widget.web.UIController
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.OkHttpClient
import okhttp3.Request
import org.koin.android.ext.android.get
import org.koin.androidx.viewmodel.ext.android.viewModel

@Route(path = RoutePath.CONTENT.MAIN_FRAGMENT)
class ContentFragment : BaseFragment() {
    private lateinit var mAgentWeb: AgentWeb
    private lateinit var mBinding: ContentFragmentMainBinding
    private val mViewModel: ContentViewModel by viewModel()
    private lateinit var mSkuRequest: WebResourceRequest
    private lateinit var mSkuPriceRequest: WebResourceRequest

    override fun onResume() {
        super.onResume()
        activity?.title = R.string.content_module_name.getString()
        immerseColor(Color.YELLOW)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        mBinding = binding(inflater, R.layout.content_fragment_main, container)
        mBinding.fbt.onClick {
            mAgentWeb.jsAccessEntrace.callJs("window._itemInfo") {
                val jdProductBean = it.parseJson(JDProductBean::class.java)
//                LogUtils.e(jdProductBean)
                analysisProductDetail(jdProductBean)
            }
            mAgentWeb.jsAccessEntrace.callJs("window._itemOnly") {
                LogUtils.e(it)
            }
        }
        mAgentWeb = AgentWeb.with(this) //传入AgentWeb的父控件。
            .setAgentWebParent(
                mBinding.root.cast()!!,
                -1,
                LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT
                )
            ) //设置进度条颜色与高度，-1为默认值，高度为2，单位为dp。
            .useDefaultIndicator(-1, 3) //设置 IAgentWebSettings。
            .useMiddlewareWebClient(object : MiddlewareWebViewClient() {
                override fun shouldInterceptRequest(
                    view: WebView,
                    request: WebResourceRequest
                ): WebResourceResponse? {
                    if (request.url.toString().contains("service/info.action")) {
                        mSkuRequest = request
                    }
                    if (request.url.toString().contains("prices/mgets")) {
                        mSkuPriceRequest = request
                    }

                    return super.shouldInterceptRequest(view, request)
                }

            }) //权限拦截 2.0.0 加入。
            .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK) //自定义UI  AgentWeb3.0.0 加入。
            .setAgentWebUIController(UIController(requireActivity())) //参数1是错误显示的布局，参数2点击刷新控件ID -1表示点击整个布局都刷新， AgentWeb 3.0.0 加入。
            .setMainFrameErrorView(
                R.layout.agentweb_error_page,
                -1
            ) //            .setWebLayout(new WebLayout(this))
            .interceptUnkownUrl() //创建AgentWeb。
            .createAgentWeb()
            .ready() //设置 WebSettings。
            //WebView载入该url地址的页面并显示。
            .go("https://item.m.jd.com/product/100012791678.html")
        return mBinding.root
    }

    private fun mockRequest(request: WebResourceRequest, ids: String): String {
        val requestUrl = request.url.toString()
        val startIndex = requestUrl.indexOf("skuids=") + 7
        val endIndex = requestUrl.indexOf("&callback=")
        val realUrl = requestUrl.replaceRange(startIndex, endIndex, ids)

        return get<OkHttpClient>().newCall(
            Request.Builder().get()
                .apply {
                    request.requestHeaders.forEach { (t, u) ->
                        addHeader(t, u)
                    }
                }
                .url(realUrl.also {
                    LogUtils.e("url      $it")
                })
                .build()
        ).execute().body?.string()!!
            .let { it.substring(it.indexOf("(") + 1 until it.lastIndexOf(")")) }
    }

    private fun analysisProductDetail(jdProductBean: JDProductBean?) {
        val ids = jdProductBean?.skuPro?.id?.keys?.joinToString(separator = ",")
        lifecycleScope.launch(Dispatchers.IO) {
            val priceStr =
                ids?.let {
                    mockRequest(
                        mSkuPriceRequest,
                        it
                    ).parseJson<List<PriceBean>>(getType<List<PriceBean>>())
                }
            val skuList = mutableListOf<Sku>()
            jdProductBean?.skuPro?.name?.forEach { entry ->
                val sku = Sku(skuName = entry.key)
                val priceBean = priceStr?.find {
                    it.id == "J_${entry.value}"
                }
                sku.price = priceBean?.p
                skuList.add(sku)
            }
            LogUtils.e(skuList)
        }
    }

}